package com.shpng.cheapenglish.action;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.shpng.cheapenglish.entity.SUser;
import com.shpng.cheapenglish.entity.SUserUnit;
import com.shpng.cheapenglish.entity.SWord;
import com.shpng.cheapenglish.manager.UserManager;
import com.shpng.cheapenglish.manager.WordManager;
import com.shpng.cheapenglish.util.StringUtils;

public class WordInputAction {

	private String unit;

	public String execute(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		String email = (String) req.getSession().getAttribute("email");
		UserManager userManager = UserManager.getInstance();
		SUser user = userManager.getUser(email);
		String words = req.getParameter("words");
		if (StringUtils.isEmpty(words)) {
			return "/pages/word-input.jsp";
		}
		String[] wordss = words.split("\\n+");
		if (StringUtils.isEmpty(unit)) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			String dateStr = sdf.format(new Date());
			String w = " - " + wordss[0];
			unit = dateStr + w;
		}
		unit = unit.trim();
		WordManager wordManager = WordManager.getInstance();
		SUserUnit suu = wordManager.getUserUnit(unit, user);
		if (suu == null) {
			suu = wordManager.saveOrUpdateUserUnit(unit, user);
		}
		for (String w : wordss) {
			w = w.trim();
			if (!"".equalsIgnoreCase(w)) {
				SWord word = wordManager.getWord(w);
				if (word == null) {
					word = wordManager.addWord(w);
				}
				wordManager.addUserWord(word, suu);
			}

		}
		return "/pages/word-input.jsp";
	}

	public String getUnit() {
		return unit;
	}

	public void setUnit(String unit) {
		this.unit = unit;
	}

}
